/**
 * @Date: 2022-03-10 20:07:43
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-14 11:08:57
 * @FilePath: \zhihuReal\controllers\commentCtl.js
 * @Description: 答案控制器
 */
const {
    SuccessModel,
    ErrorModel
} = require('../res-model/index')
const Comment = require('../model/commentsMdl')
const User = require('../model/usersMdl')

//获取评论列表
const commentList = async (ctx) => {
    //分页
    const {
        limit = 10, page = 1
    } = ctx.query
    const pagenum = Math.max(+page, 1) - 1
    const limitnum = Math.max(+limit, 1)
    //模糊搜索
    const {
        rootCommentId
    } = ctx.query
    let q = new RegExp(ctx.query.keyword)
    const list = await Comment.find({
        content: q,
        questionId: ctx.params.questionId,
        answerId: ctx.params.answerId,
        rootCommentId
    }).limit(limitnum).skip(pagenum * limitnum).populate('commentator replyTo')
    ctx.body = new SuccessModel(list)
}
//获取单个评论
const oneComment = async (ctx) => {
    const {
        fields = ''
    } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const comment = await Comment.findById(ctx.params.id).select(selectFields).populate('commentator')
    if (!comment) {
        ctx.throw(404, '评论不存在')
    } else {
        ctx.body = new SuccessModel(comment)
    }
}
//创建评论
const createComment = async (ctx) => {
    ctx.verifyParams({
        content: {
            type: 'string',
            required: true
        },
        rootCommentId: {
            type: 'string',
            required: false
        },
        replyTo: {
            type: 'string',
            required: false
        },
    })
    const commentator = ctx.state.user._id;
    const newComment = await Comment.create({
        ...ctx.request.body,
        answerId: ctx.params.answerId,
        commentator,
        questionId: ctx.params.questionId
    })
    ctx.status = 204
    ctx.body = new SuccessModel(newComment)
}
//更新评论
const updateComment = async (ctx) => {
    ctx.verifyParams({
        content: {
            type: 'string',
            required: true
        },
    })
    //只更新一级内容
    const {
        content
    } = ctx.request.body
    const newComment = await Comment.findByIdAndUpdate(ctx.params.id, content)
    ctx.body = new SuccessModel(newComment)
}
//删除评论
const removeComment = async (ctx) => {
    const comment = await Comment.findByIdAndRemove(ctx.params.id)
    if (!comment) {
        ctx.throw(404, '你要删除的评论不存在')
    }
    ctx.status = 204

}

module.exports = {
    commentList,
    oneComment,
    createComment,
    updateComment,
    removeComment,
}